#!/usr/bin/env python3
"""
主题管理器QML集成测试

演示如何将Python主题管理器与QML组件集成
"""

import sys
import os

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from element_ui.styles import (
    theme_manager,
    style_engine,
    Theme,
    ElementColors,
    create_button_style,
    create_input_style
)


class QMLThemeIntegrator:
    """QML主题集成器"""
    
    def __init__(self):
        self.theme_manager = theme_manager
        self.style_engine = style_engine
        
        # 监听主题变更
        self.theme_manager.subscribe_theme_change(self._on_theme_changed)
    
    def get_qml_theme_object(self) -> dict:
        """
        获取QML可用的主题对象
        
        返回包含所有主题变量的字典，可以直接传递给QML
        """
        current_theme = self.theme_manager.get_current_theme()
        if not current_theme:
            return {}
        
        theme_config = self.theme_manager.available_themes.get(current_theme, {})
        
        # 构建QML主题对象
        qml_theme = {
            "name": current_theme,
            "colors": {},
            "sizes": {},
            "fonts": {},
            "shadows": {},
            "transitions": {},
        }
        
        # 添加颜色变量
        colors = theme_config.get("colors", {})
        for color_name, color_value in colors.items():
            qml_theme["colors"][color_name] = color_value
            # 同时添加到根级别以便简化访问
            qml_theme[color_name] = color_value
        
        # 添加尺寸变量
        sizes = theme_config.get("sizes", {})
        for size_name, size_value in sizes.items():
            qml_theme["sizes"][size_name] = size_value
            qml_theme[size_name] = size_value
        
        # 添加其他配置
        for section in ["fonts", "shadows", "transitions"]:
            section_data = theme_config.get(section, {})
            for key, value in section_data.items():
                qml_theme[section][key] = value
                qml_theme[key] = value
        
        return qml_theme
    
    def get_component_qml_style(self, component_type: str, **kwargs) -> dict:
        """
        获取特定组件的QML样式配置
        
        Args:
            component_type: 组件类型（button, input等）
            **kwargs: 组件特定参数（如button的type和size）
        """
        if component_type == "button":
            button_type = kwargs.get("type", "default")
            size = kwargs.get("size", "medium")
            return create_button_style(button_type, size)
        
        elif component_type == "input":
            size = kwargs.get("size", "medium")
            state = kwargs.get("state", "normal")
            return create_input_style(size, state)
        
        else:
            # 通用组件样式
            return self.style_engine.apply_element_style(component_type)
    
    def generate_qml_theme_constants(self) -> str:
        """
        生成QML主题常量文件内容
        
        返回可以保存为.qml文件的主题常量定义
        """
        theme_obj = self.get_qml_theme_object()
        
        qml_content = f'''// Element UI Theme Constants
// Auto-generated from Python theme manager
// Theme: {theme_obj.get("name", "unknown")}

pragma Singleton
import QtQuick 2.15

QtObject {{
    id: theme
    
    // Theme Info
    readonly property string name: "{theme_obj.get('name', 'unknown')}"
    
    // Colors
'''
        
        # 添加颜色常量
        colors = theme_obj.get("colors", {})
        for color_name, color_value in colors.items():
            safe_name = color_name.replace('-', '_').replace('.', '_')
            qml_content += f'    readonly property string {safe_name}: "{color_value}"\n'
        
        # 添加尺寸常量
        qml_content += '\n    // Sizes\n'
        sizes = theme_obj.get("sizes", {})
        for size_name, size_value in sizes.items():
            safe_name = size_name.replace('-', '_').replace('.', '_')
            qml_content += f'    readonly property string {safe_name}: "{size_value}"\n'
        
        # 添加字体常量
        fonts = theme_obj.get("fonts", {})
        if fonts:
            qml_content += '\n    // Fonts\n'
            for font_name, font_value in fonts.items():
                safe_name = font_name.replace('-', '_').replace('.', '_')
                qml_content += f'    readonly property string {safe_name}: "{font_value}"\n'
        
        # 添加便捷方法
        qml_content += '''
    // Convenience Methods
    function getColor(colorName) {
        return theme[colorName.replace('-', '_').replace('.', '_')] || "";
    }
    
    function getSize(sizeName) {
        return theme[sizeName.replace('-', '_').replace('.', '_')] || "";
    }
}'''
        
        return qml_content
    
    def _on_theme_changed(self, event):
        """主题变更回调"""
        print(f"QML主题集成器: 主题已从 '{event.old_theme}' 切换到 '{event.new_theme}'")
        # 在实际应用中，这里应该通知QML引擎更新主题


def demo_qml_integration():
    """演示QML集成功能"""
    print("=== QML主题集成演示 ===")
    
    integrator = QMLThemeIntegrator()
    
    # 获取当前主题的QML对象
    theme_obj = integrator.get_qml_theme_object()
    print(f"当前主题: {theme_obj['name']}")
    print(f"主题颜色数量: {len(theme_obj['colors'])}")
    print(f"主题尺寸数量: {len(theme_obj['sizes'])}")
    
    # 显示部分颜色变量
    print("\n主要颜色变量:")
    key_colors = ['primary', 'success', 'warning', 'danger', 'info']
    for color in key_colors:
        value = theme_obj['colors'].get(color, 'N/A')
        print(f"  {color}: {value}")
    
    # 获取组件样式
    print("\n组件样式演示:")
    button_styles = {
        "primary-large": integrator.get_component_qml_style("button", type="primary", size="large"),
        "success-small": integrator.get_component_qml_style("button", type="success", size="small"),
        "input-normal": integrator.get_component_qml_style("input", size="medium", state="normal"),
        "input-focus": integrator.get_component_qml_style("input", size="medium", state="focus"),
    }
    
    for style_name, style_config in button_styles.items():
        print(f"  {style_name}: 高度={style_config.get('height', 'N/A')}")
    
    # 生成QML主题常量文件
    print("\n生成QML主题常量文件...")
    qml_constants = integrator.generate_qml_theme_constants()
    
    # 保存到文件
    constants_file = os.path.join(os.path.dirname(__file__), '..', 'element_ui', 'qml', 'Theme.qml')
    os.makedirs(os.path.dirname(constants_file), exist_ok=True)
    
    with open(constants_file, 'w', encoding='utf-8') as f:
        f.write(qml_constants)
    
    print(f"QML主题常量已保存到: {constants_file}")
    
    # 测试主题切换
    print("\n测试主题切换...")
    theme_manager.switch_theme("element-dark")
    
    dark_theme_obj = integrator.get_qml_theme_object()
    print(f"暗色主题背景色: {dark_theme_obj['colors'].get('bg-base', 'N/A')}")
    print(f"暗色主题文本色: {dark_theme_obj['colors'].get('text-primary', 'N/A')}")
    
    # 切换回默认主题
    theme_manager.switch_theme("element-default")
    
    print()


def demo_qml_style_generation():
    """演示QML样式生成"""
    print("=== QML样式生成演示 ===")
    
    integrator = QMLThemeIntegrator()
    
    # 生成不同类型按钮的样式
    button_types = ["default", "primary", "success", "warning", "danger", "info"]
    button_sizes = ["large", "medium", "small", "mini"]
    
    print("按钮样式矩阵:")
    print("类型\\尺寸", end="")
    for size in button_sizes:
        print(f"\t{size}", end="")
    print()
    
    for btn_type in button_types:
        print(f"{btn_type}", end="")
        for size in button_sizes:
            style = integrator.get_component_qml_style("button", type=btn_type, size=size)
            height = style.get('height', 'N/A')
            print(f"\t{height}", end="")
        print()
    
    print()


def main():
    """主函数"""
    print("Element UI Python QtQuick 组件库 - QML主题集成测试\n")
    
    demo_qml_integration()
    demo_qml_style_generation()
    
    print("QML集成测试完成！")


if __name__ == "__main__":
    main()
